package com.ly.mpayment.rest.up.dongye;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("dongye")
public class DongYeRest {
    Logger logger = Logger.getLogger(DongYeRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("dongye_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            MultiMap multiMap = Util.parceString(data);
            UpOrder order = upOrderService.findById(multiMap.getString("sporderid"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            //userid=xxxx&orderid=xxxxxxx&sporderid=xxxxx&merchantsubmittime=xxxxx&resultno=xxxxx&key=xxxxxxx (这里的xxxxx为具体的参数值)
            if(!multiMap.getString("sign").equalsIgnoreCase(MD5.md5(
                    "userid="+upShopInfo.getAppId()+
                         "&orderid="+multiMap.getString("orderid")+
                         "&sporderid="+multiMap.getString("sporderid")+
                         "&merchantsubmittime="+multiMap.getString("merchantsubmittime")+
                         "&resultno="+multiMap.getString("resultno")+
                         "&key="+upShopInfo.getUpkey()))){
                logger.info("签名错误:"+data);
                return "failt";
            }

            //orderid=DFW23020717407596154&sporderid=2c922ab985c7874d01862b3f7734737f&userid=10004703&merchantsubmittime=20230207174028&resultno=1&parvalue=100&remark1=0211002211020019994
            //&payno=0211002211020019994&fundbalance=-200.702&sign=929F30384B861F7C54CA0B9FA5BBA0D0
            if (order != null && multiMap.getString("resultno").equals("1") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("remark1") ? multiMap.getString("remark1") : multiMap.getString("resultno"));
                RechargeRest.successUpOrder.add(order);
                return "OK";
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("resultno").equals("9")) {
                order.setRemark(multiMap.getString("resultno"));
                RechargeRest.failtUpOrder.add(order);
                return "OK";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("resultno"));
                logger.info("dongye_not_found_order:" + multiMap.getString("sporderid") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("userid", shop.getAppId());
        //表示不传递商品编号
        if(!StringUtils.isBlank(order.getUpShopPro().getProductCode()) && !order.getUpShopPro().getProductCode().equals("1")){
            data.put("productid", order.getUpShopPro().getProductCode());
        }
        data.put("price", order.getUpShopPro().getUpfacevalue());
        data.put("num", 1);
        data.put("mobile", order.getUpphonenum());
        data.put("spordertime",DateUtils.getNowDateToString());
        //运营商类型，联通-lt 移动-yd 电信-dx,不参与验证，必填
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("paytype", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "yd" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "lt" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "dx" : "xx");
        //userid=xxxx&productid=xxxxxxx&price=xxxx&num=xxx&mobile=xxxxx&spordertime=xxxxxxx&sporderid=xxxxx&
        data.put("sign", MD5.md5("userid="+ shop.getAppId()+"&productid="+
                (order.getUpShopPro().getProductCode()== null || order.getUpShopPro().getProductCode().equals("1") ? "":order.getUpShopPro().getProductCode())+
                "&price="+order.getUpShopPro().getUpfacevalue()+"&num=1"+
                "&mobile="+order.getUpphonenum()+"&spordertime="+data.getString("spordertime")+
                "&sporderid="+order.getUporderuuid()+("&key="+shop.getUpkey())));

        data.put("sporderid", order.getUporderuuid());
        data.put("back_url", shop.getOrderCallAddress());
        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(), StringSort.jsonToString(data));
        logger.info("commitOrder_dongye:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = new JSONObject();
                this.iterateNodes(DocumentHelper.parseText(result).getRootElement(),json);
                logger.info("commitOrder_dongye_json:" + json);
                JSONObject items = json.getJSONObject("order");
                if (items.containsKey("resultno") && items.getString("resultno").equals("0")) {
                    this.upOrderService.updateUpOrderMsg(order,items.getString("orderid"),items.containsKey("remark1") ?
                            items.getString("remark1") : "");
                } else if (items.containsKey("resultno") && errorCode.contains(items.getString("resultno"))){
                    order.setRemark(items.getString("resultno"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, items.getString("resultno"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("5001");
        add("5002");
        add("5003");
        add("5004");
        add("5005");
        add("5008");
        add("5009");
        add("5010");
        add("5012");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("sporderid", upOrder.getUporderuuid());
        data.put("userid", shopInfo.getAppId());
        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress(), StringSort.jsonToString(data));
        logger.info("dongyequeryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            JSONObject json = new JSONObject();
            try {
                this.iterateNodes(DocumentHelper.parseText(result).getRootElement(),json);
                JSONObject items = json.getJSONObject("order");
                logger.info("queryOrder_dongye_json:" + items);

                if (items.containsKey("resultno") ) {
                    UpOrder order = upOrderService.findById(items.getString("sporderid"));
                    if (order != null && items.getString("resultno").equals("1") && order.getStatus() == Config.status[0]) {
                        order.setRemark( items.containsKey("resultno") ? items.getString("resultno") :
                                items.getString("resultno"));
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] && items.getString("resultno").equals("9") ) {
                        order.setRemark(items.getString("resultno"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,items.getString("resultno"));
                        logger.info("dongye_not_found_order:" + order.getUpphonenum());
                    }
                } else {
                    logger.info("dongye_not_found_order:" + upOrder.getUpphonenum());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
//    public static void main(String[] args) throws DocumentException {
//        JSONObject json = new JSONObject();
//        String result = "<?xml version=\"1.0\" encoding=\"GB2312\" ?> \n" +
//                " <order>\n" +
//                "  <orderid>XS090428000003</orderid>\n" +
//                "  <productid>3312</productid>\n" +
//                "  <num>1</num> \n" +
//                "  <ordercash>98.5</ordercash>\n" +
//                "  <productname> 广东移动100元直充</productname> \n" +
//                "  <sporderid>2009042800001</sporderid> \n" +
//                "  <mobile>13590101510</mobile>\n" +
//                "  <merchantsubmittime></merchantsubmittime>\n" +
//                "  <resultno>0</resultno>\n" +
//                "  <remark1>凭证号</remark1>\n" +
//                "  <fundbalance>100000</fundbalance>\n" +
//                "  </order>\n";
//        new dongyeRest().iterateNodes(DocumentHelper.parseText(result).getRootElement(),json);
//        System.out.println(json);
//    }

    /**
     * 遍历元素
     *
     * @param node
     *            元素
     * @param json
     *            将元素遍历完成之后放的JSON对象
     */
    @SuppressWarnings("unchecked")
    public void iterateNodes(Element node, JSONObject json) {
        // 获取当前元素的名称
        String nodeName = node.getName();
        // 判断已遍历的JSON中是否已经有了该元素的名称
        if (json.containsKey(nodeName)) {
            // 该元素在同级下有多个
            Object Object = json.get(nodeName);
            JSONArray array = null;
            if (Object instanceof JSONArray) {
                array = (JSONArray) Object;
            } else {
                array = new JSONArray();
                array.add(Object);
            }
            // 获取该元素下所有子元素
            List<Element> listElement = node.elements();
            if (listElement.isEmpty()) {
                // 该元素无子元素，获取元素的值
                if(!node.attributes().isEmpty()){
                    json.put(node.attribute(0).getValue(), node.getText());
                }else{
                    String nodeValue = node.getText();
                    array.add(nodeValue);
                    json.put(nodeName, array);
                }
                return;
            }
            // 有子元素
            JSONObject newJson = new JSONObject();
            // 遍历所有子元素
            for (Element e : listElement) {
                // 递归
                iterateNodes(e, newJson);
            }
            array.add(newJson);
            json.put(nodeName, array);
            return;
        }
        // 该元素同级下第一次遍历
        // 获取该元素下所有子元素
        List<Element> listElement = node.elements();
        if (listElement.isEmpty()) {
            // 该元素无子元素，获取元素的值
            if(!node.attributes().isEmpty()){
                json.put(node.attribute(0).getValue(), node.getText());
            }else{
                String nodeValue = node.getText();
                json.put(nodeName, nodeValue);
            }

            return;
        }
        // 有子节点，新建一个JSONObject来存储该节点下子节点的值
        JSONObject object = new JSONObject();
        // 遍历所有一级子节点
        for (Element e : listElement) {
            // 递归
            iterateNodes(e, object);
        }
        json.put(nodeName, object);
        return;
    }
}
